﻿using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using XjjXmm.FrameWork.ToolKit;

namespace XjjXmm.Spider.biquge
{
    internal class RegistHelper
    {
        //const string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] ({SourceContext}:{ThreadId}){Message:lj}{NewLine}{Exception}";

        const string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] ({ThreadId}) {Message:lj}{NewLine}{Exception}";


        public static void RegistLog()
        {

            LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
            .MinimumLevel.Information()

            //.Enrich.WithProperty("SourceContext", null) //加入属性SourceContext，也就运行时是调用Logger的具体类
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .Enrich.WithThreadId()
            .Enrich.WithThreadName()
            ;

            var typeInfos = ReflectKit.GetEntryAssembly().DefinedTypes
                .Where(t =>
                        t != typeof(NovelSpider)
                        && t.IsAssignableTo(typeof(ISiteSpider))
            );

            foreach (var typeInfo in typeInfos)
            {
                // ISetUpProfile? obj = (ISetUpProfile?)Activator.CreateInstance(typeInfo.AsType());
                // obj?.Regist(services);

                loggerConfiguration = loggerConfiguration.WriteTo
                    .Logger(lc => lc.Filter.ByIncludingOnly(Matching.FromSource(typeInfo.FullName))
                .WriteTo.File($"log/{typeInfo.Name}.txt", rollingInterval: RollingInterval.Day)
                );

                loggerConfiguration = loggerConfiguration.WriteTo
                   .Logger(lc => lc.Filter.ByIncludingOnly(t =>
                                   Matching.FromSource(typeInfo.FullName).Invoke(t)
                                     && t.Level == LogEventLevel.Error)
                    .WriteTo.File($"error/{typeInfo.Name}.txt", rollingInterval: RollingInterval.Day)
               );

            }

            loggerConfiguration = loggerConfiguration
                .WriteTo.Console(outputTemplate: outputTemplate)
                .WriteTo.File("log/log.txt", rollingInterval: RollingInterval.Day);

            Log.Logger = loggerConfiguration.CreateLogger();
        }

        public static IServiceCollection RegistSpider(IServiceCollection services)
        {
            services.AddScoped<HttpGBKHandel>();
            services.AddSingleton<NovelSpiderManager>();

            var typeInfos = ReflectKit.GetEntryAssembly().DefinedTypes
                        .Where(t =>
                                   t!= typeof(ISetUpProfile)
                                && t != typeof(AbstractSetUpProfile<>)
                                && t.IsAssignableTo(typeof(ISetUpProfile))
                    );

            foreach (var typeInfo in typeInfos)
            {
                ISetUpProfile? obj = (ISetUpProfile?)Activator.CreateInstance(typeInfo.AsType());
                obj?.Regist(services);

            }
            return services;
        }

        public static void RunSpider(IServiceProvider serviceProvider)
        {
            var myService = serviceProvider.GetService<NovelSpiderManager>();//.Where(t => (t is BiqoogeComSpider));


            myService.Run();
        }

        public static async void Export(IServiceProvider serviceProvider)
        {
            var myService = serviceProvider.GetService<ExportService>();//.Where(t => (t is BiqoogeComSpider));


            await myService.Run();

            Console.WriteLine("导出完成");
        }
    }
}
